﻿#include "Save.h"
#include "ui_Save.h"

Save::Save(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Save)
{
    ui->setupUi(this);
    setWindowModality(Qt::ApplicationModal);    //设置窗口模态
    setFixedSize(365,230);                      //设置固定窗口
}

Save::~Save()
{
    delete ui;
}

void Save::setData(int shang, int xia, int dong, QString benName, QString what)
{
    //初始化全局变量
    num[0] = shang;
    num[1] = xia;
    num[2] = dong;

    //初始化控件
    ui->dateTimeEdit->setDateTime(QDateTime::currentDateTime());
    ui->lineEdit_title->setText(benName + QString::number(dong));
    ui->textEdit_what->setText(what);
}

void Save::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    //设置背景图片
    painter.drawPixmap(0,0,width(),height(),QPixmap("://1.jpg"));
}

void Save::closeEvent(QCloseEvent *)
{
    hide();
}

void Save::on_pushButton_cancel_clicked()
{
    hide();
}

void Save::on_pushButton_save_clicked()
{
    if(ui->lineEdit_title->text() == "" || ui->textEdit_what->toPlainText() == ""
            || ui->textEdit_after->toPlainText() == "") {
        QMessageBox::warning(this,"请补充信息:","请将信息补充完整!");
        return;
    }
    
    //添加Sqllite数据库
    qDebug()<<QSqlDatabase::drivers();
    
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("./info.db");
    if(!db.open())
    {
        qDebug()<<"数据库打开失败!"<<db.lastError().text();
        QMessageBox::warning(this,"错误!",db.lastError().text());
        return;
    }
    
    QSqlQuery query;
    query.exec("create table info(名称 varint(50), 问事 varint(255), 占测 varint(255), 占测时间 varint(50), 本卦上 varint(50), 本卦下 varint(50), 动爻 varint(50))");  //创建表
    
    query.exec("INSERT INTO info(名称, 问事, 占测, 占测时间, 本卦上, 本卦下, 动爻) VALUES('"+ui->lineEdit_title->text() + "','"
               + ui->textEdit_what->toPlainText() + "','"
               + ui->textEdit_after->toPlainText() + "','"
               + QString::number(ui->dateTimeEdit->date().year()) + "/" + QString::number(ui->dateTimeEdit->date().month()) + "/" + QString::number(ui->dateTimeEdit->date().day()) + " " + QString::number(ui->dateTimeEdit->time().hour()) + ":" + QString::number(ui->dateTimeEdit->time().minute())+ "','"
               + QString::number(num[0]) + "','"
            + QString::number(num[1]) + "','"
            + QString::number(num[2]) + "')");
    
    query.execBatch();
    
    db.close();
    hide();
}
